using Magiq.Insert;

namespace Magiq.Databases.Insert
{
    public class DatabaseInsertStrategy<TSource, TDestination, TNew> :IInsertStrategy, IDatabaseBasedExecution
        where TDestination : class where TNew : class
    {
        private readonly IInsert<TSource,TDestination, TNew> insert;

        public DatabaseInsertStrategy(IOrmAdapter ormAdapter, IInsert<TSource,TDestination, TNew> insert)
        {
            OrmAdapter = ormAdapter;
            this.insert = insert;
        }

        #region IDatabaseBasedExecution Members

        public IOrmAdapter OrmAdapter { get; private set; }

        #endregion

        #region IInsertStrategy Members

        public int Execute()
        {
            var inserts = OrmAdapter.BuildDatabaseInserts(insert);
            var result = 0;
            foreach (var databaseInsert in inserts)
            {
                var builder = new InsertCommandBuilder(typeof(TNew), OrmAdapter, databaseInsert.Source, databaseInsert.ColumnAssignments);
                var command = builder.GetCommand();
                result += command.ExecuteNonQuerySafe();
            }
            return result;
        }

        #endregion
    }
}